package com.zaizai.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zaizai.domain.Commodity;
import com.zaizai.domain.CommodityPrice;
import com.zaizai.domain.dto.BatchUpdateRequest;
import com.zaizai.mapper.CommodityMapper;
import com.zaizai.service.ICommodityPriceService;
import com.zaizai.service.ICommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

/**
 * 商品详情Service业务层处理
 *
 * @author zaiZai
 * @date 2024-10-21
 */
@Slf4j
@Service
public class CommodityServiceImpl implements ICommodityService {
    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private ICommodityPriceService commodityPriceService;

    /**
     * 查询商品详情
     *
     * @param id 商品详情主键
     * @return 商品详情
     */
    @Override
    public Commodity selectCommodityById(Long id) {
        return commodityMapper.selectCommodityById(id);
    }

    /**
     * 查询商品详情
     *
     * @param commodity 商品详
     * @return 商品详情
     */
    @Override
    public List<Commodity> selectCommodityList(Commodity commodity) {
        log.info("接收到的查询参数: {}", commodity);
        // 确保只返回已上架的商品
        commodity.setIsShelves(1);
        List<Commodity> result = commodityMapper.selectCommodityList(commodity);
        log.info("查询结果数量: {}, typeId: {}", result.size(), commodity.getTypeId());
        return result;
    }

    /**
     * 新增商品详情
     *
     * @param commodity 商品详情
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCommodity(Commodity commodity) {
        //创建时间
        commodity.setCreateTime(new Date());
        //修改价格，转为为分
        commodity.setPrice(commodity.getPrice());
        //回显商品id
        int result = commodityMapper.insertCommodity(commodity);
        //新增的时候把当时的单价记录到单价表中
        CommodityPrice commodityPrice = CommodityPrice.builder()
                .commodityId(commodity.getId())
                .price(commodity.getPrice())
                .time(commodity.getCreateTime())
                .build();
        commodityPriceService.insertCommodityPrice(commodityPrice);
        return result;
    }

    /**
     * 修改商品详情
     *
     * @param commodity 商品详情
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCommodity(Commodity commodity) {
        log.info("Service updating commodity: {}", commodity);
        try {
            // 设置更新时间
            commodity.setUpdateTime(new Date());
            
            // 如果价格有变化，记录到历史价格表
            Commodity oldCommodity = selectCommodityById(commodity.getId());
            if (oldCommodity != null && !Objects.equals(oldCommodity.getPrice(), commodity.getPrice())) {
                CommodityPrice priceRecord = CommodityPrice.builder()
                    .commodityId(commodity.getId())
                    .price(commodity.getPrice())
                    .time(new Date())
                    .build();
                commodityPriceService.insertCommodityPrice(priceRecord);
            }
            
            int result = commodityMapper.updateCommodity(commodity);
            log.info("Update result: {}", result);
            return result;
        } catch (Exception e) {
            log.error("Error in service updating commodity:", e);
            throw e;
        }
    }

    /**
     * 批量删除商品详情
     *
     * @param ids 需要删除的商品详情主键
     * @return 结果
     */
    @Override
    public int deleteCommodityByIds(Long[] ids) {
        return commodityMapper.deleteCommodityByIds(ids);
    }

    /**
     * 删除商品详情信息
     *
     * @param id 商品详情主键
     * @return 结果
     */
    @Override
    public int deleteCommodityById(Long id) {
        return commodityMapper.deleteCommodityById(id);
    }

    @Override
    public List<Map<String, Object>> getHistoryPrices(Long commodityId) {
        return commodityMapper.getHistoryPrices(commodityId);
    }

    @Override
    public List<Map<String, Object>> getTopSellingProducts() {
        List<Map<String, Object>> topProducts = commodityMapper.getTopSellingProducts();
        
        // 处理价格显示（转换为元）和销量格式化
        for (Map<String, Object> product : topProducts) {
            if (product.get("current_price") != null) {
                Long price = (Long) product.get("current_price");
                product.put("current_price", price / 100.0); // 转换为元
            }
            
            if (product.get("total_sales") != null) {
                Long sales = ((Number) product.get("total_sales")).longValue();
                product.put("total_sales", sales);
            }
        }
        
        return topProducts;
    }

    /**
     * 查询所有商品（不分页）
     */
    @Override
    public List<Commodity> selectAllCommodities() {
        try {
            PageHelper.clearPage(); // 清除分页参数
            return commodityMapper.selectAllCommoditiesWithoutPage(); // 使用 XML 中定义的方法
        } finally {
            PageHelper.clearPage(); // 确保理
        }
    }

    @Override
    @Transactional
    public void batchUpdate(List<BatchUpdateRequest.Operation> operations) {
        for (BatchUpdateRequest.Operation op : operations) {
            switch (op.getAction().toLowerCase()) {
                case "update_price":
                    updatePrice(op);
                    break;
                case "update_serial":
                    updateSerial(op);
                    break;
                case "update_inventory":
                    updateInventory(op);
                    break;
                case "update_name":
                    updateName(op);
                    break;
                case "update_shelves":
                    updateShelves(op);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported action: " + op.getAction());
            }
        }
    }

    private void updatePrice(BatchUpdateRequest.Operation op) {
        for (Integer id : op.getTargetIds()) {
            Commodity commodity = commodityMapper.selectCommodityById(id.longValue());
            if (commodity != null) {
                long oldPrice = commodity.getPrice();
                long newPrice;
                if ("percentage".equals(op.getModifier())) {
                    double percentage = Double.parseDouble(op.getValue().toString());
                    newPrice = Math.round(oldPrice * (1 + percentage / 100));
                } else {
                    newPrice = Long.parseLong(op.getValue().toString()); // 已经是分为单位，不需要再乘100
                }
                commodity.setPrice(newPrice);
                commodityMapper.updateCommodity(commodity);
                
                // 记录价格历史
                CommodityPrice priceHistory = CommodityPrice.builder()
                    .commodityId(id.longValue())
                    .price(newPrice)
                    .time(new Date())
                    .build();
                commodityPriceService.insertCommodityPrice(priceHistory);
            }
        }
    }

    private void updateSerial(BatchUpdateRequest.Operation op) {
        for (Integer id : op.getTargetIds()) {
            Commodity commodity = commodityMapper.selectCommodityById(id.longValue());
            if (commodity != null) {
                commodity.setSerialNumber(op.getValue().toString());
                commodityMapper.updateCommodity(commodity);
            }
        }
    }

    private void updateInventory(BatchUpdateRequest.Operation op) {
        for (Integer id : op.getTargetIds()) {
            Commodity commodity = commodityMapper.selectCommodityById(id.longValue());
            if (commodity != null) {
                commodity.setInventory(Long.parseLong(op.getValue().toString()));
                commodityMapper.updateCommodity(commodity);
            }
        }
    }

    private void updateName(BatchUpdateRequest.Operation op) {
        for (Integer id : op.getTargetIds()) {
            Commodity commodity = commodityMapper.selectCommodityById(id.longValue());
            if (commodity != null) {
                commodity.setName(op.getValue().toString());
                commodityMapper.updateCommodity(commodity);
            }
        }
    }

    private void updateShelves(BatchUpdateRequest.Operation op) {
        for (Integer id : op.getTargetIds()) {
            Commodity commodity = commodityMapper.selectCommodityById(id.longValue());
            if (commodity != null) {
                commodity.setIsShelves(Integer.parseInt(op.getValue().toString()));
                commodityMapper.updateCommodity(commodity);
            }
        }
    }
}
